#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <string.h>

const int MAX_SIZE = 1024;

int main(int argc, char **argv) {
  int sock;
  struct sockaddr_in addr;
  char buf[MAX_SIZE];

  if (argc != 3) {
    printf("Usage of client: client <ip> <port>\n");
    return;
  }

  // This info should be automatically get from local network
  char *server_addr = argv[1];
  int port = atoi(argv[2]);

  printf("%s %d\n", server_addr, port);

  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("socket");
    return errno;
  }

  bzero(&addr, sizeof(addr));
  addr.sin_family = AF_INET;
  /* addr.sin_port = htons(8888); */
  /* #define SERVER_ADDR "127.0.0.1" */
  /* inet_aton(SERVER_ADDR, &addr.sin_addr.s_addr); */
  addr.sin_port = htons(port);
  inet_aton(server_addr, &addr.sin_addr.s_addr);

  if (connect(sock, (struct sockaddr *)&addr,
              sizeof(addr)) < 0) {
    perror("connect");
    return errno;
  }

  // sending hello
  printf("Enter your name:\n");
  char message[MAX_SIZE];
  scanf("%[^\n]s", message);
  message[strlen(message)] = '1';

  char command[MAX_SIZE];
  sprintf(command, "hello");
  char size[MAX_SIZE];
  strcat(command, message);
  sprintf(size, "%d", strlen(command));
  strcat(size, command);
  send(sock, size, sizeof(size), 0);

  // getting an answer
  recv(sock, buf, sizeof(message), 0);
  printf("%s\n", buf);

  for (;;) {
    // sending a message
    char message[MAX_SIZE];
    scanf("%[^\n]s", message);
    if (strlen(message) == 0) {
      continue;
    }
    
    char command[MAX_SIZE];
    sprintf(command, "send");
    char size[MAX_SIZE];
    strcat(command, message);
    sprintf(size, "%d", strlen(command));
    strcat(size, command);
    send(sock, size, sizeof(size), 0);

    // getting an answer
    recv(sock, buf, sizeof(message), 0);
    printf("%s\n", buf); 
  }

  close(sock);
  return 0;
}
